<template>
<!--  请在index.html中引入gaodeAPI在线js
  <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=mykey&plugin=AMap.Autocomplete,AMap.DistrictSearch"></script>
-->
  <div class="gaodeSearch">
    <div class="info">
      <div class="input-item">
        <el-input
          placeholder="地点搜索......"
          id="tipinput"
          class="input-with-select"
          v-model="searchCity"
        >
          <el-select
            v-model="districtSelect"
            slot="prepend"
            placeholder="请选择"
          >
            <el-option label="国家" value="country"></el-option>
            <el-option label="省/直辖市" value="province"></el-option>
            <el-option label="市" value="city"></el-option>
            <el-option label="区/县" value="district"></el-option>
            <el-option label="商圈" value="biz_area"></el-option>
          </el-select>
        </el-input>
      </div>
      <p><span id="input-info"></span></p>
    </div>
  </div>
</template>

<script>
  const locationMark = require("../assets/images/location4.png")
export default {
  name: "gaodeSearch",
  //import引入的组件需要注入到对象中才能使用",
  components: {},
  data() {
    //这里存放数据",
    return {
      //输入提示
      auto: null,
      //经度
      locationLng: null,
      //纬度
      locationLat: null,
      districtSelect: "province",
      searchCity: null
    };
  },
  //监听属性 类似于data概念",
  computed: {},
  //监控data中的数据变化",
  watch: {},
  //方法集合",
  methods: {
    autoInput() {
      AMap.plugin("AMap.Autocomplete", function() {
        const autoOptions = {
          city: "全国"
        };
        // 实例化Autocomplete
        // eslint-disable-next-line no-unused-vars
        let autoComplete = new AMap.Autocomplete(autoOptions);
      });
      AMap.event.addListener(this.auto, "select", this.select); //注册监听，当选中某条记录时会触发
    },
    //鼠标点击或者回车选中某个POI信息时触发此事件
    select(resp) {
      // console.log(resp.poi);
      // 行政区搜索使用区号作为keyword
      let name = resp.poi.name;
      //行政区划
      let polygons = [];
      // 把函数内部指到外面用
      const _this = this;
      //市级行政区Autocomplete的结果没有坐标,这种情况下用DistrictSearch行政区搜索api
      // if (resp.poi.location === "") {
      AMap.plugin("AMap.DistrictSearch", function() {
        const districtOptions = {
          subdistrict: 1, //获取边界不需要返回下级行政区
          extensions: "all" //返回行政区边界坐标组等具体信息
          // level: "city" //查询行政级别为 市
        };
        // 实例化Autocomplete
        let districtSearch = new AMap.DistrictSearch(districtOptions);
        districtSearch.setLevel(_this.districtSelect);
        districtSearch.search(name, function(status, result) {
          polygons = [];
          let bounds = null;
          if (result.districtList) {
            bounds = result.districtList[0].boundaries[0];
          }
          if (bounds) {
            for (let i = 0, l = bounds.length; i < l; i++) {
              //生成行政区划polygon
              polygons.push(bounds[i].lng);
              polygons.push(bounds[i].lat);
              // console.log(bounds[i].lng);
            }
            // console.log(bounds);
          }
          // 查询成功时，result即为对应的行政区信息
          if (status === "complete") {
            // console.log(result);
            _this.locationLng = result.districtList[0].center.lng;
            _this.locationLat = result.districtList[0].center.lat;
            _this.viewerflyToLonLat(
              _this.locationLng,
              _this.locationLat,
              500000,
              name,
              polygons
            );
          }
        });
      });
    },
    viewerflyToLonLat(lng, lat, alt, name, polygons) {
      window.viewer.entities.removeAll();
      // cesium相机飞行
      window.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(lng, lat, alt)
      });
      if (polygons.length > 0) {
        window.viewer.entities.add({
          name: name,
          polygon: {
            hierarchy: Cesium.Cartesian3.fromDegreesArray(polygons),
            material: Cesium.Color.BLUE.withAlpha(0.3)
          }
        });
      } else {
        // let pinBuilder = new Cesium.PinBuilder();
        // let pin = pinBuilder.fromColor(Cesium.Color.GREEN, 48).toDataURL();
        // console.log("polygons2");
        window.viewer.entities.add({
          name: name,
          position: Cesium.Cartesian3.fromDegrees(lng, lat),
          billboard: {
            image: locationMark,
            width:30,
            height:40,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // default
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM // default: CENTER
          }
        });
      }
    }
  },
  //生命周期 - 创建之前",数据模型未加载,方法未加载,html模板未加载
  beforeCreate() {},

  //生命周期 - 创建完成（可以访问当前this实例）",数据模型已加载，方法已加载,html模板已加载,html模板未渲染
  created() {
  },
  //生命周期 - 挂载之前",html模板未渲染
  beforeMount() {},

  //生命周期 - 挂载完成（可以访问DOM元素）",html模板已渲染
  mounted() {
    this.auto = new AMap.Autocomplete({
      input: "tipinput"
    });
    this.autoInput();
  },

  //生命周期 - 更新之前",数据模型已更新,html模板未更新
  beforeUpdate() {},
  //生命周期 - 更新之后",数据模型已更新,html模板已更新
  updated() {},
  //生命周期 - 销毁之前",
  beforeDestroy() {},
  destroyed() {},
  //生命周期 - 销毁完成",
  //如果页面有keep-alive缓存功能，这个函数会触发",
  activated() {}
};
</script>

<style scoped>
@import "https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css";
.gaodeSearch {
  position: relative;
  width: 100%;
}
.gaodeSearch .info {
  position: absolute;
  z-index: 1000;
  top: 20px;
  right: 4rem;
  padding: 0.5rem 1rem;
  background-color: rgba(0, 0, 0, 0.2);
}
</style>
<style>
  .el-input-group__prepend{
    width: 120px;
  }
</style>
